<script setup lang='ts'>
import { useCreateOrUpdateBuyerChild, useGetPca } from '@fl/api/purchase'
import { SubmitBtn } from '@fl/components'

const form = ref()
const parentId = defineModel<string>('parentId', { required: true })
const visible = defineModel<boolean>('visible', { required: true })

const title = computed(() => parentId.value ? '新增下级子公司' : '新增子公司')

const { isPending, mutate } = useCreateOrUpdateBuyerChild()

const formValues = ref({
    addr: [],
    confirmUserName: '',
    name: '',
    userName: '',
})

const { data: pcaData, isLoading: pcaLoading } = useGetPca(visible)

const pcaOptions = computed(() => {
    return pcaData.value ? pcaData.value : []
})

const columns = [
    {
        hasLabel: computed(() => false),
        label: '提示',
        prop: 'msg',
    },
    {
        label: '子公司名称',
        prop: 'name',
        width: 120,
    },
    {
        fieldProps: {
            props: { children: 'children', label: 'name', value: 'name' },
        },
        label: '公司地址',
        options: pcaOptions,
        prop: 'addr',
        valueType: 'cascader',
    },
    {
        label: '初始账号',
        prop: 'userName',
        width: 120,
    },
    {
        label: '再次输入初始账号',
        prop: 'confirmUserName',
        width: 120,
    },
]

function validateConfirmPassword(_rule: any, value: string, callback: Fn): void {
    if (value === '')
        callback(new Error('请再次输入账号'))
    else if (value !== formValues.value.userName)
        callback(new Error('两次输入密码不一致!'))
    else
        callback()
}

const rules = {
    addr: [
        {
            message: '请选择公司地址',
            required: true,
        },
    ],
    confirmUserName: [
        {
            required: true,
            validator: validateConfirmPassword,
        },
    ],
    name: [
        {
            message: '请输入子公司名称',
            required: true,
        },
    ],
    userName: [
        {
            message: '请输入初始账号',
            required: true,
        },
    ],
}

async function confirm() {
    const valid = await form.value.formInstance.validate()

    if (valid) {
        const params = {
            addr: formValues.value.addr.join('/'),
            confirmUserName: formValues.value.confirmUserName,
            name: formValues.value.name,
            parentId: parentId?.value || 0,
            userName: formValues.value.userName,
        }
        mutate(params, {
            onSuccess: () => {
                ElMessage.success('提交成功')
                cancel()
            },
        })
    }
}

function cancel() {
    visible.value = false
}

function reset() {
    // 重置数据
    parentId.value = ''
    form.value.formInstance.resetFields()
}
</script>

<template>
    <PlusDialog v-model="visible"
                :title="title"
                width="800"
                close-on-press-escape
                @cancel="cancel"
                @closed="reset"
    >
        <ElSkeleton v-if="pcaLoading"
                    animated
        />

        <PlusForm v-else
                  ref="form"
                  v-model="formValues"
                  :columns="columns"
                  :label-width="150"
                  :rules="rules"
                  :has-footer="false"
        >
            <template #plus-field-msg>
                <div class="w-full">
                    <el-alert title="初始账号请使用验证码登录,子公司创建后不可删除,请核对信息后确认"
                              type="warning"
                              show-icon
                              :closable="false"
                              center
                    />
                </div>
            </template>
        </PlusForm>

        <template #footer>
            <div class="mx-auto">
                <el-button @click="cancel">
                    取消
                </el-button>

                <SubmitBtn type="primary"
                           :loading="isPending"
                           @click="confirm"
                >
                    提交
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>
</template>
